<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商家管理</title>
    <!--引入的vue.js-->
    <script src="../../js/vue.js"></script>
    <!--引入elementUI的css-->
    <link type="text/css" rel="stylesheet" href="../../css/index.css">
    <!--引入elementUI的js-->
    <script src="../../js/index.js"></script>
    <!--引入axios.js-->
    <script src="../../js/axios.min.js"></script>
</head>
<body>
<!-- Vue应用根元素 -->
<div id="app" class="app1">
    <!-- 搜索区域 - 使用Element UI栅格系统布局 -->
    <el-row>
        <!-- 客户ID搜索框 -->
        <el-col :span="6">
            <el-input size="mini"
                      v-model="searchForm.customerId"
                      placeholder="请输入客户ID"
                      size="small">
            </el-input>
        </el-col>

        <!-- 客户名称搜索框 -->
        <el-col :span="6">
            <el-input size="mini"
                      v-model="searchForm.customerName"
                      placeholder="请输入客户名称"
                      size="small">
            </el-input>
        </el-col>

        <!-- 手机号搜索框 -->
        <el-col :span="6">
            <el-input size="mini"
                      v-model="searchForm.phone"
                      placeholder="请输入手机号"
                      size="small">
            </el-input>
        </el-col>
        <el-col :span="6">
            <el-select
                    v-model="searchForm.auditStatus"
                    placeholder="请选择审核状态"
                    size="small">
                <el-option label="全部" value=""></el-option>
                <el-option label="待审核" value="0"></el-option>
                <el-option label="已通过" value="1"></el-option>
                <el-option label="已拒绝" value="2"></el-option>
            </el-select>
        </el-col>

        <!-- 搜索和添加按钮 -->
        <el-col :span="6">
            <el-button size="mini"
                       type="primary"
                       icon="el-icon-search"
                       @click="search"
                       size="small">
                搜索
            </el-button>
            &nbsp;&nbsp;
<!--            <el-button size="mini"
                       type="primary"
                       @click="handleAdd">
                添加
            </el-button>-->
        </el-col>
    </el-row>

    <!-- 客户数据表格 -->
    <el-table :data="tableData" style="width: 100%">
        <!-- 客户ID列 -->
        <el-table-column prop="customerId" label="客户ID" width="80"></el-table-column>

        <!-- 客户名称列 -->
        <el-table-column prop="customerName" label="客户名称" width="120"></el-table-column>

        <!-- 客户身份证件列 -->
        <el-table-column prop="idCard" label="身份正好" width="120"></el-table-column>

        <!-- 手机号列 -->
        <el-table-column prop="phone" label="手机号" width="120"></el-table-column>

        <!-- 地址列 -->
        <el-table-column prop="address" label="地址" width="150"></el-table-column>

        <!-- 预付款余额列 -->
        <el-table-column prop="income" label="预付款余额" width="120"></el-table-column>

        <!-- 状态列 -->
        <el-table-column prop="status" label="状态" width="80">
            <template slot-scope="scope">
                <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
                    {{ scope.row.status === '0' ? '正常' : '停用' }}
                </el-tag>
            </template>
        </el-table-column>

        <!-- 审核状态列 -->
        <el-table-column prop="auditStatus" label="审核状态" width="100">
            <template slot-scope="scope">
                <el-tag v-if="scope.row.auditStatus === '0'" type="info">待审核</el-tag>
                <el-tag v-else-if="scope.row.auditStatus === '1'" type="success">通过</el-tag>
                <el-tag v-else type="danger">拒绝</el-tag>
            </template>
        </el-table-column>
        <!-- 审核人列 -->
        <el-table-column prop="auditBy" label="审核人" width="120">
            <template slot-scope="scope">
                {{ scope.row.auditBy || '未审核' }} <!-- 未审核时显示“未审核” -->
            </template>
        </el-table-column>

        <!-- 审核时间列 -->
        <el-table-column prop="auditTime" label="审核时间" width="180">
            <template slot-scope="scope">
                <!-- 时间格式处理：将ISO格式（含T）转为正常时间字符串 -->
                {{ scope.row.auditTime ? scope.row.auditTime.replace('T', ' ').substring(0, 19) : '未审核' }}
            </template>
        </el-table-column>
        <!-- 创建时间列 -->
        <el-table-column prop="createTime" label="创建时间" width="180">
            <template slot-scope="scope">
                {{ scope.row.createTime ? scope.row.createTime.replace('T', ' ').substring(0, 19) : '' }}
            </template>
        </el-table-column>

        <!-- 在创建时间列后添加身份证照片列 -->
        <el-table-column label="身份证照片" width="120">
            <template slot-scope="scope">
                <div v-if="scope.row.idPhotograph">
                    <el-image
                            :src="scope.row.idPhotograph"
                            :preview-src-list="[scope.row.idPhotograph]"
                            style="width: 80px; height: 80px;"
                            fit="cover"
                            lazy>
                        <div slot="error" class="image-slot">
                            <i class="el-icon-picture-outline"></i>
                        </div>
                    </el-image>
                </div>
                <div v-else>
                    <span>无</span>
                </div>
            </template>
        </el-table-column>


        <!-- 操作列 -->
        <el-table-column label="操作" fixed="right" width="200">
            <template slot-scope="scope">
                <!-- 编辑按钮 -->
                <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">
                    编辑
                </el-button>

                <!-- 删除按钮 -->
                <el-button size="mini"
                           type="danger"
                           @click="handleDelete(scope.$index, scope.row)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[3,5,10,15,20,100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>

    <!-- 添加/更新客户对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="600px">
        <!-- 表单 -->
        <el-form :model="form" :rules="rules" ref="form" label-width="100px">
            <!-- 客户名称输入框 -->
            <el-form-item label="客户名称" prop="customerName">
                <el-input v-model="form.customerName" autocomplete="off"></el-input>
            </el-form-item>

            <!-- 手机号输入框 -->
            <el-form-item label="手机号" prop="phone">
                <el-input v-model="form.phone" autocomplete="off"></el-input>
            </el-form-item>

            <!-- 身份证号输入框 -->
            <el-form-item label="身份证号" prop="idCard">
                <el-input v-model="form.idCard" autocomplete="off"></el-input>
            </el-form-item>

            <!-- 地址输入框 -->
            <el-form-item label="地址" prop="address">
                <el-input v-model="form.address" autocomplete="off"></el-input>
            </el-form-item>

            <!-- 预付款余额输入框 -->
            <el-form-item label="预付款余额" prop="income">
                <el-input v-model="form.income" autocomplete="off"></el-input>
            </el-form-item>

            <!-- 身份证照片路径输入框 -->
            <el-form-item label="身份证照片" prop="idPhotograph">
                <el-input v-model="form.idPhotograph" autocomplete="off"></el-input>
            </el-form-item>

            <!-- 关联用户ID输入框 -->
            <el-form-item label="关联用户ID" prop="userId">
                <el-input v-model="form.userId" autocomplete="off"></el-input>
            </el-form-item>

            <!-- 状态选择框 -->
            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status">
                    <el-radio label="0">正常</el-radio>
                    <el-radio label="1">停用</el-radio>
                </el-radio-group>
            </el-form-item>

            <!-- 在表单中添加身份证照片上传字段 -->
            <el-form-item label="身份证照片" prop="idPhotograph">
                <el-upload
                        class="upload-demo"
                        action="/vegetablemarketexpress/customer/uploadIdImage"
                        name="pic"
                        :on-success="handleIdPhotoSuccess"
                        :on-error="handleIdPhotoError"
                        :before-upload="beforeIdPhotoUpload"
                        :limit="1"
                        :file-list="idPhotoFileList"
                        list-type="picture">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
                </el-upload>
                <el-input v-model="form.idPhotograph" type="hidden"></el-input>
                <div v-if="form.idPhotograph">
                    <img :src="form.idPhotograph" style="width: 100px; height: 100px; margin-top: 10px;" />
                </div>
            </el-form-item>


            <!-- 备注输入框 -->
            <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="form.remark" autocomplete="off" :rows="3"></el-input>
            </el-form-item>
        </el-form>

        <!-- 对话框底部按钮 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button @click="resetForm('form')">重置</el-button>
            <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        </div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                tableData: [],              // 表格数据
                currentPage: 1,             // 当前页码
                pageSize: 5,                // 每页显示条数
                total: 0,                   // 总条数
                searchForm: {               // 搜索条件
                    customerId: '',
                    customerName: '',
                    phone: '',
                    auditStatus: '' // 新增：审核状态筛选（0=待审核，1=通过，2=拒绝）
                },
                idPhotoFileList: [],// 身份证照片上传文件列表
                title: '添加客户',           // 对话框标题
                dialogFormVisible: false,   // 客户表单对话框是否可见
                auditDialogVisible: false,  // 审核对话框是否可见
                form: {                     // 客户表单数据
                    customerId: '',
                    customerName: '',
                    idCard: '',
                    phone: '',
                    address: '',
                    income: '',
                    status: '0',
                    idPhotograph: '',
                    userId: '',
                    remark: ''
                },
                auditForm: {                // 审核表单数据
                    customerId: '',
                    customerName: '',
                    auditStatus: '',
                    auditRemark: ''
                },
                // 表单验证规则
                rules: {
                    customerName: [
                        { required: true, message: '请输入客户名称', trigger: 'blur' }
                    ],
                    phone: [
                        { required: true, message: '请输入手机号', trigger: 'blur' }
                    ],
                    idCard: [
                        { required: true, message: '请输入身份证号', trigger: 'blur' }
                    ],
                    address: [
                        { required: true, message: '请输入地址', trigger: 'blur' }
                    ]
                }
            }
        },
        created() {
            // 页面加载时加载数据
            this.loadData();
        },
        methods: {
            // 加载客户数据
            loadData() {
                let _this = this;
                // 发送POST请求获取分页数据
                axios.post('/vegetablemarketexpress/customer/selectCustomerListAndStatus', {
                    "pageNo": this.currentPage,
                    "pageSize": this.pageSize,
                    "data": this.searchForm
                }).then(function(response) {
                    if (response.data.code == 200) {
                        _this.tableData = response.data.data.list;
                        _this.total = response.data.data.total;
                    }
                }).catch(function(error) {
                    console.log(error);
                    _this.$message.error('数据加载失败');
                });
            },

            // 每页条数改变时触发
            handleSizeChange(val) {
                this.pageSize = val;
                this.currentPage = 1;
                this.loadData();
            },

            // 当前页改变时触发
            handleCurrentChange(val) {
                this.currentPage = val;
                this.loadData();
            },

            // 搜索功能
            search() {
                this.currentPage = 1;
                this.loadData();
            },

            // 提交表单
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let uri = '/vegetablemarketexpress/customer/insertCustomer';
                        if (this.title == '客户更新') {
                            uri = '/vegetablemarketexpress/customer/updateCustomer';
                        }

                        let _this = this;
                        let submitForm = JSON.parse(JSON.stringify(this.form));

                        axios.post(uri, submitForm)
                            .then(function(response) {
                                if (response.data.code == 200) {
                                    _this.$message({
                                        message: '操作成功',
                                        type: 'success'
                                    });
                                    _this.loadData();
                                    _this.dialogFormVisible = false;
                                } else {
                                    _this.$message.error('操作失败: ' + response.data.msg);
                                }
                            })
                            .catch(function(error) {
                                console.log(error);
                                _this.$message.error('操作异常');
                            });
                    } else {
                        this.$message.error('表单验证失败');
                    }
                });
            },
            // 重置表单
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },

            // 处理编辑客户
            handleEdit(index, row) {
                this.dialogFormVisible = true;
                this.title = "客户更新";
                // 深拷贝避免直接引用
                this.form = JSON.parse(JSON.stringify(row));
                // 回显身份证照片
                this.idPhotoFileList = [];
                if (this.form.idPhotograph) {
                    const fileName = this.form.idPhotograph.substring(this.form.idPhotograph.lastIndexOf('/') + 1);
                    this.idPhotoFileList.push({
                        name: fileName,
                        url: this.form.idPhotograph
                    });
                }
            },

            // 身份证照片上传成功处理
            handleIdPhotoSuccess(response, file, fileList) {
                /*if (response.code === 200) {
                    // 从正确的路径获取URL
                    const url = response.data && response.data.url ? response.data.url : response.url;
                    if (url) {
                        this.form.idPhotograph = url;
                        this.$message.success('身份证照片上传成功');
                    } else {
                        this.$message.error('身份证照片上传返回URL异常');
                    }
                } else {
                    this.$message.error('身份证照片上传失败: ' + (response.msg || '未知错误'));
                }*/
                if (response.code === 200) {
                    // 后端返回 {filePath: "图片地址", originName: "原文件名"}
                    this.form.idPhotograph = response.data.filePath;
                    this.$message.success('身份证照片上传成功');
                } else {
                    this.$message.error('身份证照片上传失败: ' + (response.msg || '未知错误'));
                }
            },

            // 身份证照片上传失败处理
            handleIdPhotoError(err, file, fileList) {
                this.$message.error('身份证照片上传失败');
            },

            // 身份证照片上传前检查
            beforeIdPhotoUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('身份证照片只能上传 JPG/PNG 格式!');
                    return false;
                }
                if (!isLt2M) {
                    this.$message.error('身份证照片大小不能超过 2MB!');
                    return false;
                }
                return true;
            },

            // 处理删除客户
            handleDelete(index, row) {
                this.$confirm('此操作将永久删除该客户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let _this = this;
                    // 发送删除请求
                    axios.delete('/vegetablemarketexpress/customer/deleteCustomerById?customerId=' + row.customerId)
                        .then(function(response) {
                            if (response.data.code == 200) {
                                _this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                _this.loadData();
                            } else {
                                _this.$message.error('删除失败: ' + response.data.msg);
                            }
                        })
                        .catch(function(error) {
                            console.log(error);
                            _this.$message.error('删除异常');
                        });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        }
    });
</script>
</body>
</html>
